/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.bomt.service.impl;

import com.comac.ins.bomt.domain.DetailStandardV2Bom;
import com.comac.ins.bomt.domain.DetailStrengthV2Bom;
import com.comac.ins.bomt.domain.vo.*;
import com.comac.ins.bomt.repository.BomRepositoryV2;
import com.comac.ins.bomt.service.BomCoreServiceV2;
import com.comac.ins.common.core.domain.model.LoginUser;
import com.comac.ins.common.biz.utils.BizAssertUtil;
import com.comac.ins.common.mybatis.helper.BaseEntityHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * Bom核心转化服务实现V2
 *
 * @author zhanghongyi
 * @date 2024 /8/28
 * @description BomCoreServiceV2Impl
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BomCoreServiceV2Impl implements BomCoreServiceV2 {

    private final BomRepositoryV2 bomRepositoryV2;

    @Value("${bom.codePath.joinChar:,}")
    private String fullCodePathJoinChar;


    @Override
    public Map<String, List<DetailStandardV2BomVo>> convertOriginToStandard(LoginUser loginUser, List<DetailOriginalV2BomVo> originalBomVos,List<String> deleteWords) {
        Map<String, List<DetailOriginalV2BomVo>> groupedVos = originalBomVos.stream().collect(Collectors.groupingBy(vo -> vo.getMainSection()+"#"+vo.getSection(), LinkedHashMap::new, Collectors.toList()));
        Map<String, List<DetailStandardV2BomVo>> groupedStandardVos = new LinkedHashMap<>();
        for (Map.Entry<String, List<DetailOriginalV2BomVo>> entry : groupedVos.entrySet()) {
            List<DetailStandardV2BomVo> detailStandardBomVos = new ArrayList<>();
            AtomicLong ord = new AtomicLong();
            for (DetailOriginalV2BomVo originalBomVo : entry.getValue()) {
                DetailStandardV2BomVo detailStandardV2BomVo = DetailStandardV2BomVo.createFromOriginalBom(originalBomVo);
                detailStandardV2BomVo.setOrd(ord.getAndIncrement());
                if ((!StringUtils.equals(detailStandardV2BomVo.getLevel(), "1")) && StringUtils.containsAny(detailStandardV2BomVo.getName(), deleteWords.toArray(new String[0]))) {
                    log.debug("match keyword,code:{}: name:{} level:{} is deleted", detailStandardV2BomVo.getCode(), detailStandardV2BomVo.getName(), detailStandardV2BomVo.getLevel());
                    //非根节点且名称包含关键词的抛弃掉
                    continue;
                }
                detailStandardBomVos.add(detailStandardV2BomVo);
            }
            groupedStandardVos.put(entry.getKey(), detailStandardBomVos);
            log.info("standard group:{} size:{}", entry.getKey(), detailStandardBomVos.size());
        }
        BizAssertUtil.notEmpty(groupedStandardVos, "生成的标准装机清单为空");
        return groupedStandardVos;
    }

    public List<DetailStrengthV2Bom> convertStandardToStrength(LoginUser loginUser, List<DetailStandardV2Bom> standardBomDetails,List<String> deleteWords,String groupCode) {
        AtomicLong ord = new AtomicLong();
        List<DetailStrengthV2Bom> result = new ArrayList<>();
        Integer gCnt = 1;
        String gLevel = "2";
        for (int i = 0; i < standardBomDetails.size(); i++) {
            DetailStandardV2Bom detail = standardBomDetails.get(i);
            String code = StringUtils.split(detail.getCode(), ".")[0];
            if (checkNotTargetItem(detail)) {
                //忽略非目标项
                continue;
            }
            if (checkG40Begin(detail)) {
                gCnt = detail.getCnt();
                gLevel = detail.getLevel();
                i++;
                detail = standardBomDetails.get(i);
            }
            if (checkG40End(detail, gLevel, code)) {
                gCnt = 1;
                gLevel = detail.getLevel();
            }
            for (int j = 0; j < gCnt * detail.getCnt(); j++) {
                //Q:VBA原版逻辑，比较费解，g40begin后的第一条使用g40begin的code覆盖
                detail.setCode(code);
                result.add(convertDetailStandardToStrength(loginUser, ord.getAndIncrement(), detail,groupCode));
            }
        }
        //排除命中删除关键字的条目
        result = result.stream().filter(detail -> {
            boolean f = (!StringUtils.containsAny(detail.getName(), deleteWords.toArray(new String[0]))) || StringUtils.equals(detail.getLevel(), "1");
            if (!f) {
                log.debug("match keyword, code:{}: name:{} level:{} is deleted", detail.getCode(), detail.getName(), detail.getLevel());
            }
            return f;
        }).toList();
        return result;
    }

    /**
     * 判断是否为目标项
     *
     * @param detail the detail
     * @return the boolean
     */
    private boolean checkNotTargetItem(DetailStandardV2Bom detail) {
        String code = StringUtils.split(detail.getCode(), ".")[0];
        boolean isTargetItem = code.startsWith("R") || StringUtils.isNumeric(code.substring(0, Math.min(code.length(), 4)));
        return !isTargetItem;
    }

    /**
     * 判断是否为G40开始
     *
     * @param detail the detail
     * @return the boolean
     */
    private boolean checkG40Begin(DetailStandardV2Bom detail) {
        String code = StringUtils.split(detail.getCode(), ".")[0];
        if (StringUtils.equals(detail.getAircraftModel(), "C919")) {
            //C919
            String conditionS = code.substring(code.length() - 2);
            if (StringUtils.isNumeric(conditionS)) {
                int conditionI = Integer.parseInt(conditionS);
                return conditionI >= 40 && conditionI < 50 && !code.startsWith("R");
            } else {
                return false;
            }
        } else {
            //C929
            String conditionS = code.substring(code.length() - 3);
            if (StringUtils.isNumeric(conditionS)) {
                int conditionI = Integer.parseInt(conditionS);
                return conditionI >= 400 && conditionI < 500 && !code.startsWith("R");
            } else {
                return false;
            }
        }
    }

    /**
     * 是否G40结束
     *
     * @param detail     the detail
     * @param beginLevel the begin level
     * @return the boolean
     */
    private boolean checkG40End(DetailStandardV2Bom detail, String beginLevel, String code) {
        return StringUtils.equals(detail.getLevel(), beginLevel) || code.startsWith("R");
    }

    private DetailStrengthV2Bom convertDetailStandardToStrength(LoginUser loginUser, Long ord, DetailStandardV2Bom detail,String groupCode) {
        DetailStrengthV2Bom item = new DetailStrengthV2Bom();
        item.setCode(StringUtils.split(detail.getCode(), ".")[0]);
        item.setLevel(StringUtils.equals("1", detail.getLevel()) ? "1" : "1.1");
        item.setName(detail.getName());
        item.setFullCodePath(detail.getFullCodePath());
        item.setVersion(detail.getVersion());
        item.setVersionNum("1");
        item.setOrd(ord);
        item.setAta(detail.getAta());
        item.setGroupType(groupCode);
        item.setSubGroupType(detail.getSubGroupType());
        item.setAircraftModel(detail.getAircraftModel());
        item.setTrack(detail.getTrack());
        item.setSubTrack(detail.getSubTrack());
        item.setStandardDetailId(detail.getId());
        item.setOriginalDetailId(detail.getOriginalDetailId());
        BaseEntityHelper.fillCreateByAndUpdateBy(detail, loginUser);
        return item;
    }
}
